<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>音乐播放器 - 随机推荐</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <header>
        <div class="container">
            <h1>🎵 音乐播放器</h1>
        </div>
    </header>

    <main>
        <div class="container">
            <!-- 搜索框 -->
            <div class="search-section">
                <div class="search-box">
                    <input type="text" id="searchInput" placeholder="🔍 搜索歌曲或歌手...">
                    <button id="searchButton">搜索</button>
                    <button id="randomButton">🎲 随机推荐</button>
                </div>
            </div>

            <div class="page-header">
                <h2 id="pageTitle">{% if keyword %}🔍 "{{ keyword }}" 的搜索结果{% else %}🎲 随机推荐歌曲{% endif %}</h2>
                <p id="pageSubtitle">{% if keyword %}找到 {{ songs|length }} 首相关歌曲{% else %}为您随机推荐 {{ songs|length }} 首精彩歌曲{% endif %}</p>
            </div>

            <div class="songs-container" id="songsContainer">
                {% if songs %}
                    {% for song in songs %}
                    <div class="song-item" data-song-id="{{ song.id }}" data-song-src="{{ song.src }}">
                        <div class="song-info">
                            <div class="song-title">{{ song.name }}</div>
                            <div class="song-artist">{{ song.artist }}</div>
                        </div>
                        <div class="song-actions">
                            <button class="btn-download" data-song-id="{{ song.id }}">⬇️ 下载</button>
                        </div>
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="no-songs">
                        <p>暂无歌曲数据</p>
                    </div>
                {% endif %}
            </div>
        </div>
    </main>

    <!-- 下载链接模态框 -->
    <div id="downloadModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h3>📥 选择下载链接</h3>
            <div id="downloadLinks"></div>
        </div>
    </div>

    <!-- 音频播放器 -->
    <div id="audioPlayer" class="audio-player">
        <audio id="player" controls>
            您的浏览器不支持音频播放。
        </audio>
    </div>

    <footer>
        <div class="container">
            <p>&copy; 2025 音乐播放器. 保留所有权利.</p>
        </div>
    </footer>

    <script src="{{ url_for('static', filename='js/script.js') }}"></script>
    <script>
        // 搜索功能
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('searchInput');
            const searchButton = document.getElementById('searchButton');
            const randomButton = document.getElementById('randomButton');
            const pageTitle = document.getElementById('pageTitle');
            const pageSubtitle = document.getElementById('pageSubtitle');
            const songsContainer = document.getElementById('songsContainer');

            // 搜索按钮点击事件
            searchButton.addEventListener('click', function() {
                const keyword = searchInput.value.trim();
                if (keyword) {
                    searchSongs(keyword);
                }
            });

            // 回车键搜索
            searchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    const keyword = searchInput.value.trim();
                    if (keyword) {
                        searchSongs(keyword);
                    }
                }
            });

            // 随机推荐按钮点击事件
            randomButton.addEventListener('click', function() {
                loadRandomSongs();
            });

            // 搜索歌曲函数
            function searchSongs(keyword) {
                // 显示加载状态
                pageTitle.textContent = `🔍 "${keyword}" 的搜索结果`;
                pageSubtitle.textContent = '正在搜索中...';

                // 调用API搜索歌曲
                fetch(`/api/search?keyword=${encodeURIComponent(keyword)}&limit=50`)
                    .then(response => response.json())
                    .then(data => {
                        displaySongs(data, keyword);
                        pageSubtitle.textContent = `找到 ${data.length} 首相关歌曲`;
                    })
                    .catch(error => {
                        console.error('搜索失败:', error);
                        songsContainer.innerHTML = '<div class="no-songs"><p>搜索失败，请稍后重试</p></div>';
                        pageSubtitle.textContent = '搜索失败';
                    });
            }

            // 加载随机歌曲函数
            function loadRandomSongs() {
                // 通过页面刷新来加载随机歌曲（保持URL一致性）
                window.location.href = '/';
            }

            // 显示歌曲列表函数
            function displaySongs(songs, keyword) {
                if (songs.length === 0) {
                    songsContainer.innerHTML = '<div class="no-songs"><p>未找到相关歌曲</p></div>';
                    return;
                }

                let songsHtml = '';
                songs.forEach(song => {
                    songsHtml += `
                    <div class="song-item" data-song-id="${song.id}" data-song-src="${song.src}">
                        <div class="song-info">
                            <div class="song-title">${song.name}</div>
                            <div class="song-artist">${song.artist}</div>
                        </div>
                        <div class="song-actions">
                            <button class="btn-download" data-song-id="${song.id}">⬇️ 下载</button>
                        </div>
                    </div>
                    `;
                });

                songsContainer.innerHTML = songsHtml;
                
                // 重新绑定事件
                bindDownloadButtons();
                bindSongClickEvents();
            }

            // 重新绑定下载按钮事件
            function bindDownloadButtons() {
                const downloadButtons = document.querySelectorAll('.btn-download');
                downloadButtons.forEach(button => {
                    button.addEventListener('click', function(e) {
                        e.stopPropagation();
                        const songId = this.getAttribute('data-song-id');
                        showDownloadLinks(songId);
                    });
                });
            }

            // 重新绑定歌曲点击事件
            function bindSongClickEvents() {
                const songItems = document.querySelectorAll('.song-item');
                songItems.forEach(item => {
                    item.addEventListener('click', function(e) {
                        if (e.target.classList.contains('btn-download')) {
                            return;
                        }
                        
                        const songId = this.getAttribute('data-song-id');
                        const songSrc = this.getAttribute('data-song-src');
                        playSong(songSrc);
                        
                        // 高亮当前播放的歌曲
                        document.querySelectorAll('.song-item').forEach(item => {
                            item.style.backgroundColor = 'white';
                        });
                        this.style.backgroundColor = '#e3f2fd';
                    });
                });
            }

            // 显示下载链接
            function showDownloadLinks(songId) {
                const modal = document.getElementById('downloadModal');
                const downloadLinksContainer = document.getElementById('downloadLinks');
                
                downloadLinksContainer.innerHTML = '<div class="loading"></div> 正在获取下载链接...';
                modal.style.display = 'block';
                
                fetch(`/api/song/${songId}/download_urls`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.length > 0) {
                            let linksHtml = '';
                            data.forEach(link => {
                                linksHtml += `<a href="${link.value}" target="_blank" class="download-link">${link.type}</a>`;
                            });
                            downloadLinksContainer.innerHTML = linksHtml;
                        } else {
                            downloadLinksContainer.innerHTML = '<p>暂无可用下载链接</p>';
                        }
                    })
                    .catch(error => {
                        console.error('获取下载链接失败:', error);
                        downloadLinksContainer.innerHTML = '<p>获取下载链接失败，请稍后重试</p>';
                    });
            }

            // 播放歌曲
            function playSong(songSrc) {
                const player = document.getElementById('player');
                if (player) {
                    player.src = songSrc;
                    player.play()
                        .then(() => {
                            console.log('开始播放歌曲');
                        })
                        .catch(error => {
                            console.error('播放失败:', error);
                            alert('播放失败，请检查音频链接是否有效');
                        });
                }
            }

            // 绑定模态框事件
            function bindModalEvents() {
                const modal = document.getElementById('downloadModal');
                const closeBtn = document.querySelector('.close');
                
                if (closeBtn) {
                    closeBtn.addEventListener('click', function() {
                        modal.style.display = 'none';
                    });
                }
                
                window.addEventListener('click', function(event) {
                    if (event.target === modal) {
                        modal.style.display = 'none';
                    }
                });
                
                document.addEventListener('keydown', function(event) {
                    if (event.key === 'Escape') {
                        modal.style.display = 'none';
                    }
                });
            }

            // 初始化绑定
            bindModalEvents();
        });
    </script>
</body>
</html>